/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.zhaojiu.rest;

import me.zhengjie.annotation.Log;
import me.zhengjie.modules.zhaojiu.domain.Attendance;
import me.zhengjie.modules.zhaojiu.domain.AttendanceDetail;
import me.zhengjie.modules.zhaojiu.domain.enumeration.CheckInStatus;
import me.zhengjie.modules.zhaojiu.service.AttendanceDetailService;
import me.zhengjie.modules.zhaojiu.service.AttendanceService;
import me.zhengjie.modules.zhaojiu.service.StudentService;
import me.zhengjie.modules.zhaojiu.service.TeacherService;
import me.zhengjie.modules.zhaojiu.service.dto.*;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @author Jiayin Wei
* @date 2021-12-09
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "宏志助航：考勤管理")
@RequestMapping("/api/attendance")
public class AttendanceController {

    private final AttendanceService attendanceService;
    private final AttendanceDetailService attendanceDetailService;
    private final TeacherService teacherService;
    private final StudentService studentService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('attendance:list')")
    public void download(HttpServletResponse response, AttendanceQueryCriteria criteria) throws IOException {
        attendanceService.download(attendanceService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询考勤")
    @ApiOperation("查询考勤")
    @PreAuthorize("@el.check('attendance:list')")
    public ResponseEntity<Object> query(AttendanceQueryCriteria criteria, Pageable pageable){
        if(criteria.getTeacherId() != null){
            TeacherDto teacherDto = teacherService.findByUserId(criteria.getTeacherId());
            criteria.setTeacherId(teacherDto.getTeacherId());
        }
        return new ResponseEntity<>(attendanceService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增考勤")
    @ApiOperation("新增考勤")
    @PreAuthorize("@el.check('attendance:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Attendance resources){
        //保存考勤信息
        AttendanceDto attendanceDto = attendanceService.create(resources);

        //保存考勤明细信息
        //1 拉取考勤对应班级的学生名单
        StudentQueryCriteria criteria = new StudentQueryCriteria();
        criteria.setClassId(resources.getClassId());
        List<StudentDto> students = studentService.queryAll(criteria);
        //2 获取考勤教师姓名
        TeacherDto teacherDto = teacherService.findById(attendanceDto.getTeacherId());
        String teacherName = "";
        if(teacherDto != null) teacherName = teacherDto.getName();
        //3 将学生的考勤情况保存到考勤明细表中，默认签到情况为“-1：待点名”
        for (StudentDto student : students) {
            AttendanceDetail attendanceDetail = new AttendanceDetail();
            attendanceDetail.setAttendanceId(attendanceDto.getAttendanceId());
            attendanceDetail.setStudentId(student.getStudentId());
            attendanceDetail.setIsCheckIn(CheckInStatus.UNCALL);
            //attendanceDetail.setCreateBy(teacherName);
            attendanceDetailService.create(attendanceDetail);
        }

        return new ResponseEntity<>(attendanceDto,HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改考勤")
    @ApiOperation("修改考勤")
    @PreAuthorize("@el.check('attendance:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody Attendance resources){
        attendanceService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除考勤")
    @ApiOperation("删除考勤")
    @PreAuthorize("@el.check('attendance:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Long[] ids) {
        attendanceService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("获取考勤次数")
    @ApiOperation("获取考勤次数")
    @PreAuthorize("@el.check('attendance:list')")
    @PostMapping(value = "/count/{teacherId}/{classId}/{courseId}")
    @ResponseBody
    public ResponseEntity<Object> count(@PathVariable("teacherId") Long teacherId,
                     @PathVariable("classId") Long classId,
                     @PathVariable("courseId") Long courseId){
        if(teacherId != null){
            TeacherDto teacherDto = teacherService.findByUserId(teacherId);
            teacherId = teacherDto.getTeacherId();
        }
        return new ResponseEntity<>(attendanceService.count(teacherId, classId, courseId), HttpStatus.OK);
    }
}
